package may.test_5_27;

import java.util.ArrayList;

public class Solution {
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        if(lists == null || lists.size() == 0) {
            return null;
        }
        ListNode list1 = null;
        for (int i = 0; i < lists.size(); i++) {
            ListNode list2 = lists.get(i);
            list1 = merge(list1,list2);
        }
        return list1;
    }
    public ListNode merge(ListNode list1,ListNode list2) {
        if(list1 == null && list2 != null) {
            return list2;
        }
        if(list2 == null && list1 != null) {
            return list1;
        }
        if(list1 == null && list2 == null) {
            return null;
        }
        if(list1.val <= list2.val) {
            list1.next = merge(list1.next,list2);
            return list1;
        } else {
            list2.next = merge(list2.next,list1);
            return list2;
        }
    }
}
